const webpack = require('webpack');
const HappyPack = require('happypack');
const { resolve } = require('path');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
const path = require('path');
const glob = require('glob');

const HtmlWebpackPlugin = require('html-webpack-plugin');
// 打包成额外的文件
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const htmlWebpackPluginArray = [];
const entries = {};
glob.sync('./src/pages/**/**.js').forEach(paths => {
  const chunk = paths.split('./src/pages/')[1].split('/')[0]

  entries[chunk] = paths;
  const filename = chunk + '.html';

  let chunkName = './src/pages/' + chunk
  const htmlConf = {
    filename: filename,
    template: 'html-withimg-loader!' + path.resolve(chunkName, filename),
    chunks: [chunk]
  };
  htmlWebpackPluginArray.push(new HtmlWebpackPlugin(htmlConf));
});
module.exports = {
  entry: entries,
  module: {
    rules: [
      {
        test: /\.js$/,
        /*use: 'babel-loader?cacheDirectory=true',*/
        loader: 'happypack/loader?id=happybabel', // 将loader换成happypack
        include: [resolve('src')], // src是项目开发的目录
        exclude: /node_modules/
      },
    ]
  },
  plugins: [
    /* new HtmlWebpackPlugin({
      template: './src/index/index.html',
      title: 'Production'
    }), */
    new HappyPack({
      id: 'happybabel',
      loaders: ['babel-loader?cacheDirectory=true'],
      threadPool: happyThreadPool,
      verbose: true
    }),
    new webpack.HashedModuleIdsPlugin(),
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "css/[name].[hash].css",
      chunkFilename: '[id].[hash].css'
    }),
    // 解决vender后面的hash每次都改变
    new webpack.HashedModuleIdsPlugin(),
    ...htmlWebpackPluginArray
  ],
  output: {
    filename: 'js/[name].[hash].js',
    path: path.resolve(__dirname, 'dist')
  },
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      maxSize: 0,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
};